<#assign ctx=springMacroRequestContext.contextPath />
<#include "/macro/simple.ftl">

<@header title="WebRtc 本地测试">
    <link href="${ctx}/resource/common/css/signin.css" rel="stylesheet">
    <#--<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>-->
    <#--<script src="${ctx}/resource/webrtc/dto.js"/>-->

    <style>

    </style>

    <script type="text/javascript">
        var localStream = null;
        var localPeerConnection = null;
        var remotePeerConnection = null;
        var audioContext = null;

        function test() {
            alert('333333333333333');
        }

        window.onload = function() {
            init();
        }

        function init() {
            navigator.mediaDevices.getUserMedia({ video: true, audio: true })
                .then(openLocalStream)
                .catch(function(e) {
                    alert('getUserMedia() error: ' + e);
                });

        }

        function call() {
            var tip = document.getElementById("tip");
            tip.innerText = '1111111111111111111' + localStream;
            if (localPeerConnection === null) {
                createLocalPeerConnection();

                if (localStream !== null) {
                    tip.innerText = '222222222222' + localStream;
                    try {
                        localStream.getTracks().forEach(track=> {
                            tip.innerText = '333333333' + track;
                            if (localPeerConnection !== null) {
                                localPeerConnection.addTask(track, localStream)
                            }
                        });
                    } catch (e) {
                        localPeerConnection.addStream(localStream);
                    }
                }

                createOffer();
            }
            if (remotePeerConnection === null) {
                createRemotePeerConnection();
            }

            let remoteVideo = document.getElementById("localVideo");
            remoteVideo.onloadedmetadata = () => {
                let stream = null;
                try {
                    stream = remoteVideo.captureStream();
                    console.log('音视频流', stream);

                    // 设置分辨率为1920*1080
                    const constraints = {
                        width: { min: 1280, ideal: 1920 },
                        height: { min: 720, ideal: 1080 },
                        advanced: [{ width: 1920, height: 1080 }, { aspectRatio: 1.333 }],
                    };
                    const videoTrack = stream.getVideoTracks()[0]; // 获取视频轨道
                    videoTrack
                        .applyConstraints(constraints)
                        .then(() => {
                            console.log('分辨率设置成功');
                            console.log(
                                '更新后的 constraints=',
                                stream.getVideoTracks()[0].getConstraints(),
                            );
                        })
                        .catch(error => {
                            console.error('分辨率设置失败:', error);
                        });
                } catch (error) {}
            };
        }

        function openLocalStream(stream) {
            console.info('Open local video stream');
            var localVideo = document.getElementById("localVideo");
            localVideo.srcObject = stream;
            localStream = stream;
        }

        function createLocalPeerConnection() {
            localPeerConnection = new RTCPeerConnection();

            localPeerConnection.addEventListener('iceconnectionstatechange', (event) => {
                console.info('onconnectionstatechange: ', event);
            });
            localPeerConnection.onconnectionstatechange = (event) => {
                console.info('onconnectionstatechange: ', event);
            };
            localPeerConnection.onicecandidate = handleIceCandidate;
        }

        function createOffer() {
            console.info('createOffer');
            localPeerConnection.createOffer().then((offerSdp)=> {
                console.info("1111111", offerSdp);
                localPeerConnection.setLocalDescription(offerSdp);
                var sdp = new RTCSessionDescription({
                    'type': 'offer',
                    'sdp': offerSdp.sdp
                });

                remotePeerConnection.setRemoteDescription(offerSdp);
                remotePeerConnection.createAnswer().then((answerSdp)=> {
                    console.info("answerSdp", answerSdp);
                    remotePeerConnection.setLocalDescription(answerSdp);
                    var answerSdp2 = new RTCSessionDescription({
                        'type': 'answer',
                        'sdp': answerSdp.sdp
                    });
                    localPeerConnection.setRemoteDescription(answerSdp).catch((error)=> {
                        console.error('error:', error);
                    });
                    console.info('setRemoteDescription22');
                });
                console.info('setRemoteDescription');
            });
        }

        function handleIceCandidate(event) {
            console.log('local Candidate:', event.candidate);
            if (event.candidate) {
                remotePeerConnection.addIceCandidate(event.candidate);
            } else {
                console.log('End of candidates.');
            }
        }

        function handleRemoteStreamAdded(event) {
            var remoteVideo = document.getElementById("remoteVideo");
            remoteVideo.srcObject = event.stream;
        }

        function createRemotePeerConnection() {
            console.info('createRemotePeerConnection');
            remotePeerConnection = window.pc = new RTCPeerConnection();

            remotePeerConnection.onicecandidate = handleRemoteIceCandidate;
            remotePeerConnection.ontrack = async (event) => {
                console.log(event)
                if (event.track.kind === "video") {
                    var player = document.getElementById('remoteVideo')
                    let remoteStream = event.streams[0];

                    player.srcObject = remoteStream;
                    player.controls = true

                }
            }
        }

        function handleRemoteIceCandidate(event) {
            console.log('remote Candidate:', event.candidate);
            if (event.candidate) {
                localPeerConnection.addIceCandidate(event.candidate);
            } else {
                console.log('End of candidates.');
            }
        }

        // 是否开启麦克风
        function setAudioStatus(isEnable) {
            if (localStream !== null) {
                localStream.getAudioTracks().forEach(track => {
                    track.enabled = isEnable;
                });
            }
        }

        // 是否开启摄像头
        function setVideoStatus(isEnable) {
            if (localStream !== null) {
                localStream.getVideoTracks().forEach(track => {
                    track.enabled = isEnable;
                });
            }
        }

        // 调整音量
        function adjustVolume(volumeNumber) {
            if (audioContext === null) {
                audioContext = new (window.AudioContext || window.webkitAudioContext)()
            }
            // 创建 MediaStreamAudioSourceNode
            const source = audioContext.createMediaStreamSource(stream);

            // 创建 GainNode 来控制音量
            const gainNode = audioContext.createGain();
            gainNode.gain.value = volumeNumber; // 设置放大倍数，这里设置为2倍

            // 连接音源和增益节点
            source.connect(gainNode);

            // 将增益节点连接到扬声器或进一步处理
            gainNode.connect(audioContext.destination);
        }

    </script>
</@header>

<@body>
    <span id="tip">000000000000000000</span>
    <div class="container">
        <h1 class="h3 mb-3 font-weight-normal">WebRtc 本地测试</h1>
        <div class="row">
            <div class="col-sm">
                <video id="localVideo" height="200" width="200" autoplay="autoplay" controls></video>
            </div>
            <div class="col-sm">
                <video id="remoteVideo" height="200" width="200" autoplay="autoplay" controls></video>
            </div>
        </div>

        <div class="row">
            <button onclick="call()">call</button>
            <button onclick="test()">test</button>
        </div>
    </div>
    <div>
        <button onclick="setAudioStatus(true)">开启语音</button>
        <button onclick="setAudioStatus(false)">关闭语音</button>
        <button onclick="setVideoStatus(true)">开启摄像头</button>
        <button onclick="setVideoStatus(false)">关闭摄像头</button>
        <button onclick="adjustVolume(2)">增大音量</button>
        <button onclick="adjustVolume(1)">关闭增大音量</button>
    </div>
</@body>

<@footer>
</@footer>
